//
//  AppDelegate.m
//  QDMetroClient
//
//  Created by YueWen on 2018/12/28.
//  Copyright © 2018 YueWen. All rights reserved.
//


#import "AppDelegate+JCBrightness.h"
#import "QDTabBarController.h"
#import "QDMetroClient-Swift.h"

#import <UMShare/UMShare.h>
#import <UShareUI/UShareUI.h>
#import <UMAnalytics/MobClick.h>
#import <UMCommon/UMCommon.h>

#import <IQKeyboardManager/IQKeyboardManager.h>

/// 支付
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>

/// 推送
#import <JPush/JPUSHService.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

/// 活动盒子
#import "HeziSDKManager.h"

@interface QDMetroAppDelegate () <JPUSHRegisterDelegate>

@end

@implementation QDMetroAppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
#if DEBUG
    
    // for iOS
    [[NSBundle  bundleWithPath:@"/Applications/InjectionIII.app/Contents/Resources/iOSInjection.bundle"] load];
#endif

    UIWindow *window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
    self.window = window;
    
    self.window.rootViewController = QDTabBarController.sharedInstance;
    
    //配置IQKeyboardManager
    IQKeyboardManager.sharedManager.enableAutoToolbar = false;
    [IQKeyboardManager.sharedManager.disabledDistanceHandlingClasses addObject:QDUnionSignViewController.self];
    
    //进行登录读
    [QDUserInfoModel readFromNativePlace];
    //友盟配置
    [self setUMShareSDK];
    //微信配置
    [WXApi registerApp:WX_APP_KEY];
    //活动盒子
    [self setHeZiSDK];
    //追加3D Touch
    [self createShortcutItems];
    //配置极光推送
    [self setupjPush:launchOptions];
    [self.window makeKeyAndVisible];
    //检测重要信息以及版本更新
    [self checkImportantMessageOrVersion];
    
    return YES;
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    [self brightnessGraduallyResumeBrightnessWhenWillResignActive];
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    application.applicationIconBadgeNumber = 0;
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [self brightnessGraduallySetBrightnessHighWhenBecomeActive];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - Others

/// 注册活动盒子
- (void)setHeZiSDK {
    
    [[HeziSDKManager sharedInstance] configureKey:HZ_APP_KEY];
    [[HeziSDKManager sharedInstance] openDebug:false];
    [[HeziSDKManager sharedInstance] initialize];
}


/// 注册友盟分享
- (void)setUMShareSDK {
    
    [MobClick setCrashReportEnabled:YES];
    [UMConfigure initWithAppkey:UM_APP_KEY channel:UM_APP_CHANNEL];
    [MobClick setScenarioType:E_UM_NORMAL];
    [UMConfigure setEncryptEnabled:YES];//打开加密传输
}


/// 设置极光推送
- (void)setupjPush:(NSDictionary *)launchOptions {
    
    if (@available(iOS 10.0, *)){
        
        JPUSHRegisterEntity *entity = [[JPUSHRegisterEntity alloc]init];
        entity.types = UNAuthorizationOptionBadge | UNAuthorizationOptionSound |UNAuthorizationOptionAlert;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
        
    } else {
        
        UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        [JPUSHService registerForRemoteNotificationTypes:types categories:nil];
    }
    
    [JPUSHService setupWithOption:launchOptions appKey:JPUSH_APP_KEY channel:JPUSH_CHANNEL apsForProduction:JPUSH_IS_PRODUCTION];
    [JPUSHService crashLogON];
}


/// 上报token
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


#pragma mark - <JPUSHRegisterDelegate>

// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification NS_AVAILABLE_IOS(12.0) {
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //从通知界面直接进入应用
        
    }else{
        //从通知设置界面进入应用
    }
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler NS_AVAILABLE_IOS(10.0) {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    
    completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}


#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmismatched-parameter-types"
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler NS_AVAILABLE_IOS(10.0) {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}
#pragma clang diagnostic pop

/// 
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}


/// 
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required, For systems with less than or equal to iOS 6
    [JPUSHService handleRemoteNotification:userInfo];
}


#pragma mark - 3DTouch

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler {
    
    [NSNotificationCenter.defaultCenter postNotificationName:@"QDShortcutItemCompleteNotificationName" object:nil userInfo:@{@"type" : shortcutItem.type}];
    completionHandler(true);
}


@end
